﻿using System.Collections.Generic;
using System.Linq;
using CooliteExample.Model;
using CooliteExamples.Code.DTO;
using CooliteExamples.Core.Exceptions;

namespace CooliteExamples.Code.DAL
{
    public static class AuthorDAL
    {
        public static List<Author> GetAuthors()
        {
            using (BookManagerEntities context = new BookManagerEntities())
            {
                return context.AuthorSet.OrderBy(a => a.Name).ToList().Select(a => new Author(a)).ToList();
            }
        }
        
        public static List<Author> GetAuthorsForBook(int bookId)
        {
            using (BookManagerEntities context = new BookManagerEntities())
            {
                mBook book = context.BookSet.FirstOrDefault(b => b.BookId == bookId);
                return book == null ? new List<Author>() : book.Authors.OrderBy(a => a.Name).Select(a => new Author(a)).ToList();
            }
        }

        public static int SaveAuthor(Author author)
        {
            using (BookManagerEntities context = new BookManagerEntities())
            {
                mAuthor authorToSave = new mAuthor();
                if (author.AuthorId > 0)
                    authorToSave = context.AuthorSet.FirstOrDefault(a => a.AuthorId == author.AuthorId);

                authorToSave.Name = author.AuthorName;

                if (author.AuthorId == 0)
                    context.AddToAuthorSet(authorToSave);

                context.SaveChanges();

                return authorToSave.AuthorId;
            }
        }

        public static void DeleteAuthor(Author author)
        {
            using (BookManagerEntities context = new BookManagerEntities())
            {
                mAuthor theAuthor = context.AuthorSet.Include("Books").FirstOrDefault(a => a.AuthorId == author.AuthorId);
                if (theAuthor == null)
                    throw new BookManagerOperationException("Could not find the desired author");

                if (theAuthor.Books.Count > 0)
                    throw new BookManagerOperationException("Cannot delete an Author with associated books");

                context.DeleteObject(theAuthor);
                context.SaveChanges();
            }
        }
    }
}
